package cn.sytton.taffecloud.common.api.sentinel.fallback;

import cn.hutool.aop.ProxyUtil;
import cn.sytton.taffecloud.common.base.exception.ApiException;
import cn.sytton.taffecloud.common.base.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 统一FallbackFactory熔断降级处理
 *
 * @author skyrock
 */
@Slf4j
@Component
public class CommonFallbackFactory<T> extends AbstractFallbackFactory<T>{

    @Value("${feign.global-exception:true}")
    private boolean enabledGlobalException;

    @Override
    public T create(Method method, Throwable cause) {
        return createFallbackService(cause, method.getDeclaringClass());
    }

    private T createFallbackService(Throwable ex, Class<?> targetClass) {
        log.error("[服务调用异常]"+ex.getMessage(), ex);
        return ProxyUtil.newProxyInstance((proxy, method, args) -> {
            if (enabledGlobalException) {
                //启用全局异常，对于seata的分布事物有效
                throw new ApiException(ex.getMessage());
            } else {
                return R.fail(ex.getMessage());
            }
        }, targetClass);
    }
}
